package cn.cyh.imeans.bat;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 框选屏幕区域
 */
public class ScreenSelector extends JFrame {

    private Point startPoint = null; // 鼠标按下的起始点
    private Point endPoint = null; // 鼠标释放的结束点
    private Rectangle selectionRect = null; // 选择的矩形区域

    public ScreenSelector() {
        // 设置窗口属性
        setUndecorated(true); // 去除边框和标题栏
        //setBackground(new Color(0, 0, 0, 0)); // 设置背景透明
        setOpacity(0.5f); // 设置窗口透明度
        setSize(Toolkit.getDefaultToolkit().getScreenSize()); // 设置窗口大小与屏幕一致
        setLocationRelativeTo(null); // 窗口居中显示

        // 添加鼠标监听器
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                startPoint = e.getPoint();
                endPoint = startPoint;
                selectionRect = new Rectangle(startPoint);
                repaint(); // 重绘窗口以显示选择框
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                endPoint = e.getPoint();
                if (selectionRect != null) {
                    System.out.println("Selected area: " + selectionRect);
                    dispose(); // 选择完成后关闭窗口

                    Test.POINT_MAP.put("x", selectionRect.x);
                    Test.POINT_MAP.put("y", selectionRect.y);
                    Test.POINT_MAP.put("width", selectionRect.width);
                    Test.POINT_MAP.put("height", selectionRect.height);
                    try {
                        SelectScreenCompare.compare();
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        });

        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                endPoint = e.getPoint();
                selectionRect.setBounds(
                        Math.min(startPoint.x, endPoint.x),
                        Math.min(startPoint.y, endPoint.y),
                        Math.abs(endPoint.x - startPoint.x),
                        Math.abs(endPoint.y - startPoint.y)
                );
                repaint();
            }
        });
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (selectionRect != null) {
            // 绘制选择框
            g.setColor(Color.BLUE);
            g.drawRect(selectionRect.x, selectionRect.y, selectionRect.width, selectionRect.height);
            g.dispose();
        }
    }

}
